<?php

namespace App\Http\Controllers\Port;

use App\Models\UserInfo;
use App\Models\UserLibraryInfo;
use App\Validate\UserInfoValidate;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ScoreRuleController;
use App\Models\ReadingTask;
use App\Models\ReadingTaskExecute;
use App\Models\ReadingTaskExecuteDatabase;
use App\Models\ScoreInfo;
use App\Models\ScoreLog;
use App\Models\SignScore;
use App\Models\SystemInfo;
use App\Models\UserWechatInfo;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/**
 * 用户基本信息
 */
class UserInfoController extends Controller
{
    public $model = null;
    public $libraryInfoModel = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new UserInfo();
        $this->libraryInfoModel = new UserLibraryInfo();
        $this->validate = new UserInfoValidate();
    }

    /**
     * 获取用户积分明细
     * @param token ：用户 token
     * @param page 页数
     * @param limit 限制条数
     */
    public function scoreList()
    {
        $user_id = $this->request->user_info['id'];
        $account_id = $this->request->user_info['account_id'];
        //根据具体业务，增减积分
        $md5_key = md5('getBorrowInfo' . $user_id . $account_id);
        $md5_val = Cache::get($md5_key);
        if (empty($md5_val) && !empty($user_id) && !empty($account_id)) {
            $scoreRuleObj = new ScoreRuleController();
            $scoreRuleObj->getBorrowInfo($user_id, $account_id);
            Cache::put($md5_key, $user_id, 1800); //半个小时执行一次即可/
        }

        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;

        $data = ScoreLog::select('id', 'score', 'type', 'type_id', 'intro', 'create_time')->where('account_id', $account_id)->orderByDesc('id')->paginate($limit)->toArray();

        if (empty($data['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $data = $this->disPageData($data);
        $data['score'] = DB::table(config('other.score_table'))->where('id', $account_id)->value('score');

        foreach ($data['data'] as $key => $val) {
            if ($val['type_id'] === 0 || $val['type_id'] === '0') {
                $data['data'][$key]['type_icon'] = '兑';
            } elseif (empty($val['type_id'])) {
                $data['data'][$key]['type_icon'] = '其';
            } else {
                $data['data'][$key]['type_icon'] = ScoreInfo::where('id', $val['type_id'])->value('type_icon');
                $data['data'][$key]['type_icon'] =  $data['data'][$key]['type_icon'] ?  $data['data'][$key]['type_icon'] : '其';
            }
        }

        return $this->returnApi(200, "获取成功", true, $data);
    }


    /**
     * 个人中心首页
     * @param token ：用户 token 必选
     */
    public function index()
    {
        $account_id = $this->request->user_info['account_id'];
        $user_id = $this->request->user_info['id'];
        $default_head_img = $this->getImgAddrUrl() . 'default/default_head_img.png';

        $data['head_img'] = $default_head_img;
        $data['nickname'] = '';
        $data['account'] = '';
        $data['username'] = '';
        $data['system_info_number'] = 0;
        $data['is_unread_info'] = false;
        $data['score'] = '-';
        $data['end_time'] = '';
        $data['activity_number'] = 0;
     //   $data['goods_number'] = 0;
        $data['qr_url'] = '';
        $data['qr_code'] = '';
        $data['status_card'] = '';
        $data['is_sign'] = false;
        $data['lib_name'] = config('other.lib_name'); //图书馆名称
        $scoreRuleObj = new ScoreRuleController();
        $invite_user = $scoreRuleObj->getScoreByType(2); //开启积分配置就有，没有就关闭
        $data['invite_user'] = $invite_user ? true : false; //是否显示邀请二维码按钮

        //   if ($user_id) {
        $user_info = UserInfo::where('id', $user_id)->first();
        $data['qr_url'] = $user_info['qr_url'];
        $data['qr_code'] = $user_info['qr_code'];
        if (!empty($user_info['wechat_id'])) {
            $wechat_info = UserWechatInfo::where('id', $user_info['wechat_id'])->first();

            $data['head_img'] = stripos($wechat_info['head_img'], 'http') !== false ? $wechat_info['head_img'] : $this->getImgAddrUrl() . $wechat_info['head_img'];
            $data['nickname'] = $wechat_info['nickname'];
        }
        if ($account_id) {
            $library_info = UserLibraryInfo::where('id', $account_id)->first();
            $data['account'] = $library_info['account'];
            $data['username'] = $library_info['username'];
            $data['end_time'] = $library_info['end_time'];
            $data['status_card'] = $library_info['status_card'];
            $data['score'] = DB::table(config('other.score_table'))->where('id', $account_id)->value('score');
        } else {
            $data['account'] = '';
            $data['username'] = '';
            $data['end_time'] = '';
            $data['status_card'] = '';
            $data['score'] = '-';
        }

        //获取系统消息个数
        $data['system_info_number'] = SystemInfo::where('user_id', $user_id)->count();
        //是否有未读消息
        $data['is_unread_info'] = SystemInfo::where('user_id', $user_id)->where('is_look', 2)->count() ? true : false;
        //获取活动个数
        //  $activityApplyObj = new ActivityApply();
        //  $data['activity_number'] = $activityApplyObj->getMyActivityNumber($user_id);

        //获取是否签到
        $is_sign = SignScore::where('user_id', $user_id)->where('date', date('Y-m-d'))->first();
        $data['is_sign'] = $is_sign ? true : false;

        //是否显示我的积分按钮
        if (config('other.is_need_score') === true) {
            $is_view_score_button = ScoreInfo::where('is_open', 1)->first();
            $data['is_view_score_button'] = $is_view_score_button ? true : false;
            //获取显示签到按钮
            if ($is_view_score_button) {
                $is_view_sign_button = ScoreInfo::where('is_open', 1)->where(function ($query) {
                    $query->orwhere('type', 13)->orwhere('type', 14);
                })->first();
                $data['is_view_sign_button'] = $is_view_sign_button ? true : false;
            } else {
                $data['is_view_sign_button'] = false;
            }
        } else {
            $data['is_view_score_button'] = false;
            $data['is_view_sign_button'] = false;
        }

        //获取我的阅读任务
        $field = ['id', 'title', 'img', 'start_time', 'end_time', 'browse_num', 'intro', 'create_time'];
        $readingTaskModel = new ReadingTask();
        $reading_task = $readingTaskModel->lists($field, null, $user_id, 1, null, null, null, null, 1);

        //判断阅读任务进度
        $readingTaskExecuteModel = new ReadingTaskExecute();
        $readingTaskExecuteDatabaseModel = new ReadingTaskExecuteDatabase();
        foreach ($reading_task['data'] as $key => $val) {
            $reading_task['data'][$key]['intro'] = strip_tags($val['intro']);
            $progress = $readingTaskExecuteModel->where('user_id', $user_id)->where('task_id', $val['id'])->value('progress');
            $reading_task['data'][$key]['progress'] = $progress ? $progress : 0; //阅读总进度
            $reading_task['data'][$key]['status'] = $readingTaskModel->getReadingTaskStatus($val['id']); //阅读任务状态
            // //查询下面的电子书数据库
            // $task_database_list = $this->taskDatabaseModel->getReadingTaskDatabaseList($val['id']);
            // //获取阅读进度
            // foreach ($task_database_list as $key => $val) {
            //     $database_progress = $readingTaskExecuteDatabaseModel->where('user_id', $user_id)
            //         ->where('task_id', $val['id'])->where('database_id', $val['database_id'])->value('progress');
            //         $task_database_list[$key]['progress'] = $database_progress ? $database_progress : 0;
            // }
            // $res['data'][$key]['task_database_list'] = $task_database_list; //阅读数据库
        }
        $data['reading_task'] = $reading_task['data'];
        $data['reading_task_total'] = $reading_task['total'];

        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 修改头像 和 昵称
     * @param token 用户guid
     * @param nickname 用户昵称
     * @param head_img 用户头像
     */
    public function wechatInfoChange()
    {
        $wechat_id = $this->request->user_info['wechat_id'];
        $nickname = $this->request->nickname;
        $head_img = $this->request->head_img;
        if (empty($nickname) && empty($head_img)) {
            return $this->returnApi(202, "参数错误");
        }
        if (mb_strlen($nickname) > 10) {
            return $this->returnApi(202, "用户昵称不能超过10个字符");
        }

        $userWechatInfo = new UserWechatInfo();
        $res = $userWechatInfo->wechatInfoChange($wechat_id, $nickname, $head_img);
        if ($res) {
            return $this->returnApi(200, "修改成功", true);
        }
        return $this->returnApi(202, "修改失败");
    }
}
